package org.edu.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.RequestAware;
import org.edu.model.Dept;
import org.edu.model.TreeNode;
import org.edu.service.DeptService;
import org.edu.service.TreeNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
/**
 * <h2>医院部门 Action</h2>
 * <p>已在方法上注明方法作用</p>
 * @author 谢圣强
 * @version 2.0
 */

//声明此类为控制层的类
@Controller
@ParentPackage("struts-default")
@Namespace("/Department")
// 表示继承的父包
// 表示当前Action所在命名空间
public class DeptAction extends ActionSupport implements RequestAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(DeptAction.class);
	private Map<String, Object> request;
	private String id;
	private String pid;
	private Dept dept;

	// 删除用
	private String nexid;
	private boolean isparent;
	private String parent;

	@Autowired
	private DeptService deptService;
	@Autowired
	private TreeNodeService treeNodeService;

	/**
	 * 初始化加载
	 */
	@Action(value = "dept", results = { @Result(name = "success", location = "/examples/section.jsp") })
	public String execute() throws Exception {
		try {
			request.put("dept",
					deptService.show(Integer.parseInt(null == id ? "1" : id)));
		} catch (Exception e) {
			request.put("tip", "加载失败");
			logger.info("加载失败");
		}

		return SUCCESS;
	}

	/**
	 * 加载树 id 从那个节点开始加载
	 */
	@Action(value = "deptTreeNode")
	public void deptTreeNode() {
		HttpServletResponse response = ServletActionContext.getResponse();
		// 以下代码从JSON.java中拷过来的
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			logger.info("开始加载树");
			out.println(treeNodeService.list(id).toString());
		} catch (Exception e) {
			logger.info("加载树失败");
		}
		out.flush();
		out.close();
	}

	/**
	 * 判断 用户创建的id 是否重复
	 */
	@Action(value = "isIDRepeat")
	public void isIDRepeat() {
		HttpServletResponse response = ServletActionContext.getResponse();
		// 以下代码从JSON.java中拷过来的
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// treenode 表为主表
		try {
			if (null == treeNodeService.show(Integer.parseInt(id))) {
				logger.info("id可用");
				out.println("1");
			} else {
				logger.info("id不可用");
				out.println("0");
			}
		} catch (Exception e) {
			logger.info("失败，id可能不正确");
			out.println("0");
		}
		out.flush();
		out.close();
	}

	/**
	 * 新增节点 ajax 没有用到
	 */
	@Action(value = "addtree")
	public void addTreeNode() {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		TreeNode t = new TreeNode();
		t.setId(dept.getDeptno());
		t.setName(dept.getDeptname());
		System.out.println(dept.getDeptname());
		t.setPid(Integer.parseInt(pid));
		logger.info("树结构生成");

		dept.setTreenode(t);
		treeNodeService.save(t);
		deptService.save(dept);
		logger.info("部门生成");
		out.println("添加成功");
		out.flush();
		out.close();
	}

	/**
	 * 修改
	 * 
	 * @return
	 */
	@Action(value = "editdeptTree", results = { @Result(name = "success", location = "/examples/section.jsp") })
	public String editDeptTree() {
		try {
			logger.info("获取修改后数据,开始修改：");
			System.out.println(dept.getDeptname());
			deptService.update(dept);

			// 初始加载那个部门信息
			request.put("dept", deptService.show(dept.getDeptno()));

			// 刷新

			System.out.println(isparent);
			if (isparent) {// 父节点
				request.put("refDeptTreeNode", true);
			} else {// 子节点
				request.put("refDeptparentTreeNode", true);
				request.put("refDeptparentTreeNodeid",
						treeNodeService.show(dept.getDeptno()).getPid());
				request.put("selecttree", dept.getDeptno());// 选择那个节点
			}
		} catch (Exception e) {
			request.put("tip", "异常");
			logger.info("刷新失败，参数不正确引起");
		}
		return SUCCESS;
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@Action(value = "deleteeptTree", results = { @Result(name = "success", location = "/examples/section.jsp") })
	public String deleteDeptTree() {

		// System.out.println("选择id"+id);
		// System.out.println("相邻节点id"+nexid);
		// System.out.println("是否父项"+isparent);
		// System.out.println("父id"+parent);

		logger.info("开始执行删除：");
		try {
			treeNodeService.delete(Integer.parseInt(id), isparent);
			treeNodeService.setCont(0);

			// 初始加载那个部门信息
			request.put("dept", deptService.show(Integer
					.parseInt(null == nexid ? "1" : nexid)));
			// 刷新
			request.put("refDeptparentTreeNode", true);
			request.put("refDeptparentTreeNodeid", parent);
			request.put("selecttree", nexid);// 选择那个节点
		} catch (Exception e) {
			logger.info("删除失败，请检查参数或数据库");
			request.put("tip", "删除失败");
		}
		return SUCCESS;
	}

	/**
	 * 增加树
	 * 
	 * @return
	 */
	@Action(value = "adddeptTree", results = { @Result(name = "success", location = "/examples/section.jsp") })
	public String adddeptTree() {
		try {
			TreeNode t = new TreeNode();
			t.setId(dept.getDeptno());
			t.setName(dept.getDeptname());
			System.out.println(dept.getDeptname());
			t.setPid(Integer.parseInt(pid));
			logger.info("树结构生成");

			dept.setTreenode(t);
			treeNodeService.save(t);
			deptService.save(dept);
			logger.info("部门生成");
			// 初始加载那个部门信息
			request.put("dept",
					deptService.show(Integer.parseInt(null == pid ? "1" : pid)));

			if (isparent) {// 父节点
				request.put("refDeptTreeNode", true);
			} else {// 子节点
				request.put("refDeptparentTreeNode", true);// 调用函数
				request.put("refDeptparentTreeNodeid",
						treeNodeService.show(Integer.parseInt(pid)).getPid());// 刷新节点id
				request.put("selecttree", dept.getDeptno());// 选择那个节点
			}
		} catch (Exception e) {
			logger.info("增加失败，请检查参数或数据库");
			request.put("tip", "增加失败");
		}
		return SUCCESS;
	}

	public String downloadStencil() {
		return SUCCESS;
	}

	public void setRequest(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		this.request = arg0;

	}

	public Map<String, Object> getRequest() {
		return request;
	}

	public Dept getDept() {
		return dept;
	}

	public void setDept(Dept dept) {
		this.dept = dept;

	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getPid() {
		return pid;
	}

	public void setPid(String pid) {
		this.pid = pid;
	}

	public String getNexid() {
		return nexid;
	}

	public void setNexid(String nexid) {
		this.nexid = nexid;
	}

	public boolean isIsparent() {
		return isparent;
	}

	public void setIsparent(boolean isparent) {
		this.isparent = isparent;
	}

	public String getParent() {
		return parent;
	}

	public void setParent(String parent) {
		this.parent = parent;
	}

}
